package edu.friday.common.security.service;

import edu.friday.common.constant.Constants;
import edu.friday.common.security.LoginUser;
import edu.friday.utils.IdUtils;
import edu.friday.utils.RedisCache;
import edu.friday.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class TokenService {
    @Value("${token.header}")
    private String header;
    @Value("${token.secret}")
    private String secret;
    @Value("${token.expireTime}")
    private int expireTime;
    protected static final long MILLIS_SECOND=1000;
    protected static final long MILLIS_MINUTE=60*MILLIS_SECOND;
    private static final Long MILLIS_MINUTE_TEN=20*60*1000L;
    @Autowired
    private RedisCache redisCache;
    public String createToken(LoginUser loginUser) {
        String token= IdUtils.fastUUID();
        loginUser.setToken(token);
        refreshToken(loginUser);
        Map<String,Object> claims=new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY,token);
        return createToken(claims);
    }

    private void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime()+expireTime*MILLIS_MINUTE);
        String userKey=getTokenKey(loginUser.getToken());
        redisCache.setCacheObject(userKey,loginUser,expireTime, TimeUnit.MINUTES);
    }

    private String createToken(Map<String,Object> claims){
        String token = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512,secret).compact();
        return token;
    }
    private String getTokenKey(String uuid){
        return Constants.LOGIN_TOKEN_KEY+uuid;
    }

    public LoginUser getLoginUser(HttpServletRequest request) {
        String token=getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            Claims claims=parseToken(token);
            String uuid= (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey=getTokenKey(uuid);
            LoginUser user=redisCache.getCacheObject(userKey);
            return user;
        }
        return null;
    }

    private Claims parseToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    private String getToken(HttpServletRequest request){
        String token= request.getHeader(header);
        if (StringUtils.isNotEmpty(token)&&token.startsWith(Constants.TOKEN_PREFIX)) {
            token=token.replace(Constants.TOKEN_PREFIX,"");
        }
        return token;
    }

    public void verifyToken(LoginUser loginUser) {
        long expireTime=loginUser.getExpireTime();
        long currentTime=System.currentTimeMillis();
        if (expireTime-currentTime<=MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }
}
